﻿/* ----------------------------------------------------------------------------
 * Copyright (c) Philip Stears 
 *
 * This source code is subject to terms and conditions of the Microsoft Public 
 * License (Ms-PL).
 * 
 * By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 * 
 * To request a copy of the Microsoft Public License, send a request by email
 * to license@connectbasic.net.
 *
 * This notice must not be removed from this software.
 * ---------------------------------------------------------------------------- */

namespace ConnectBasic.ObjectModel
{
    using System;
    using ConnectBasic.Execution;
    using DlrExpression = Microsoft.Linq.Expressions.Expression;

    /// <summary>
    /// Represents a statement which exits a given scope.
    /// </summary>
    public class ExitScopeStatement : StatementNodeBase
    {
        private BasicTokenKind mTokenKind;

        /// <summary>
        /// Initializes a new instance of the <see cref="ExitScopeStatement" />.
        /// </summary>
        /// <param name="scopeKind">The kind of scope to be exited, which must be a keyword token which begins a scope, e.g. <see cref="BasicTokenKind.KeywordFor" />.</param>
        public ExitScopeStatement(BasicTokenKind scopeKind)
        {
            switch (scopeKind)
            {
                case BasicTokenKind.KeywordFor:
                case BasicTokenKind.KeywordWhile:
                case BasicTokenKind.KeywordSub:
                case BasicTokenKind.KeywordFunction:
                    break;
                default:
                    throw new ArgumentOutOfRangeException("scopeKind");
            }

            mTokenKind = scopeKind;
        }

        public override DlrExpression Compile(BasicCodeGenerator gen)
        {
            var endLabel = gen.GetFlowExitLabel(mTokenKind);

            if (endLabel == null)
            {
                throw new Exception("Label not found!");
            }
            else
            {
                return DlrExpression.Goto(endLabel);
            }
        }
    }
}
